import axios from 'axios';
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import 'element-plus/theme-chalk/el-message.css'
import "element-plus/theme-chalk/el-message-box.css";


const BASE_URL = import.meta.env.VITE_API_URL // 接口地址 在env.dev | env.prod 文件中定义


// 创建 Axios 实例
const api: AxiosInstance = axios.create({
  baseURL: BASE_URL,  // 设置基础 URL
  timeout: 10000, // 请求超时设置
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {

    if (!config.headers) {
      throw new Error(
        `好像没有请求头哦`
      );
    }
    // 请求统一添加token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${window.localStorage.getItem('token')}`;
    }

    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  async (response) => {
    const result = await response.data;

    if (result.code === 200) {
      return Promise.resolve(result);
    } else {
      result !== "" ? ElMessage.error(result.msg) : ElMessage.error('系统出错')
      throw new Error(result)
    }

  },
  (error: any) => {

    if (error.response.data) {
      const { statusCode, message } = error.response.data;
      // token 过期,重新登录
      if (statusCode === 401) {
        ElMessageBox.confirm('当前页面已失效，请重新登录', '失效', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          window.localStorage.clear();
          window.location.href = '#/login';
        });
      } else {
        ElMessage({
          message: message || '系统出错',
          type: 'error'
        });
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default api;

